--debug interception for remote train control
local debug_state = false
if debug_state then
	if event.channel=="touch" and event.msg.send_train then digiline_send("send_train","") return end
end


--some basic settings
local occupied = "^[colorize:#34ebd5"	--colour of occupied sections
local offset_x = 0.0					--positioning track icons
local offset_y = -0.4					--positioning track icons
local icon_h = 0.8						--track icon sizes
local icon_w = 1						--track icon sizes
local bg = {['W']=12.4,['H']=6}			--background size

--[[shorthand for the icons
diag_u = "switchpanel_diag.png"
diag_d = "switchpanel_diag.png^[transformFX"

sw_u_cr = "switchpanel_switch_CR.png"
sw_u_st = "switchpanel_switch_ST.png"
sw_u_rev_cr = "switchpanel_switch_CR.png^[transformFX"
sw_u_rev_st = "switchpanel_switch_ST.png^[transformFX"
sw_d_cr = "switchpanel_switch_CR.png^[transformFY"
sw_d_st = "switchpanel_switch_ST.png^[transformFY"
sw_d_rev_cr = "switchpanel_switch_CR.png^[transformR180"
sw_d_rev_st = "switchpanel_switch_ST.png^[transformR180"

swd_u_st = "switchpanel_switch_diag_ST.png"
swd_u_cr = "switchpanel_switch_diag_CR.png"
swd_u_rev_st = "switchpanel_switch_diag_ST.png^[transformFX"
swd_u_rev_cr = "switchpanel_switch_diag_CR.png^[transformFX"
swd_d_st = "switchpanel_switch_diag_ST.png^[transformFY"
swd_d_cr = "switchpanel_switch_diag_CR.png^[transformFY"
swd_d_rev_cr = "switchpanel_switch_diag_CR.png^[transformR180"
swd_d_rev_st = "switchpanel_switch_diag_ST.png^[transformR180"

cnr_u = "switchpanel_corner.png"
cnr_d = "switchpanel_corner.png^[transformFY"
cnr_u_rev = "switchpanel_corner.png^[transformR180"
cnr_d_rev = "switchpanel_corner.png^[transformFX"
]]--

--function to assemble rotatable icon strings
local ico = function(variant,rotation,state)
	local parts = {
		['sw'] = "switch_",
		['swd'] = "switch_diag_",
		['diag'] = "diag",
		['cnr'] = "corner",

		['u'] = "",
		['d'] = "^[transformFY",
		['u_rev'] = "^[transformFX",
		['d_rev'] = "^[transformR180",
	}
	if state == nil then state = "" end
	return string.format("switchpanel_%s%s.png%s",parts[variant],state,parts[rotation])
end

-- static icons
local lin = "switchpanel_line.png"
local eol = "switchpanel_eol.png"
local eol_rev = eol.."^[transformFX"
local background = "switchpanel_background.png"
local blank = ""


--utility functions
local tableLength = function(T)
  local count = 0
  for _ in pairs(T) do count = count + 1 end
  return count
end

local update = false

local maps = {
	[1] = {
		['header'] = {
			{command="addlabel",label="<--- WEST",X=icon_w*1,Y=0},
			{command="addlabel",label="EAST --->",X=icon_w*7,Y=0},
			{command="addlabel",label="MAIN STATION",X=bg.W/3,Y=0}
		},
		['base_map'] = {
			{blank,				blank,				ico("cnr","u",nil),	lin,lin,		ico("cnr","u_rev",nil),	},
			{blank,				{"main_sw3"},		lin,				lin,lin,		lin,					{"main_sw5"},	},
			{{"main_sw1"},		lin,				lin,				lin,lin,		lin,					lin,			{"main_sw7"}}	,
			{blank,				ico("cnr","u",nil),	lin,				lin,lin,		lin,					lin,			{"main_sw8"}}	,
			{{"main_sw2"},		{"main_sw4"},		lin,				lin,lin,		lin,					{"main_sw6"},	},
			{blank,				blank,				ico("cnr","d",nil),	lin,lin,		ico("cnr","d_rev",nil),	},
	
		},
		['labels'] = {
			{blank,	blank,	blank,	"Platform 1"},
			{blank,	"SW3",	blank,	"Platform 2",blank,blank,{"SW5","under"}},
			{"SW1",	blank,	blank,	"Platform 3",blank,blank,blank,{"SW7","under"}},
			{blank,	blank,	blank,	"Platform 4",blank,blank,blank,"SW8"},
			{"SW2",	"SW4",	blank,	"Platform 5",blank,blank,"SW6"},
			{blank,	blank,	blank,	"Platform 6"}
		},
		['sections'] = {
			{blank,			blank,			"417397",	{"417397"},	"417397",	"619097",},
			{blank,			"344217",		"201022",	{"201022"},	"201022",	"201022",	"619097",},
			{{"186996"},	"186996",		"498166",	{"498166"},	"498166",	"498166",	"498166",	"657546"},
			{blank,			"767660",		"767660",	{"767660"},	"767660",	"767660",	"767660",	"170582"},
			{{"012237"},	"012237",		"857538",	{"857538"},	"857538",	"857538",	"142366",},
			{blank,			blank,			"078069",	{"078069"},	"078069",	"078069",},
		},
		['points'] = {
			['main_sw1'] = {['button_pos'] = {['x']=0.5,['y']=5.4},['pos']={['x']=433,['y']=2,['z']=-84},['icon'] = {"sw","u"}},
			['main_sw2'] = {['button_pos'] = {['x']=0.5,['y']=6.4},['pos']={['x']=435,['y']=2,['z']=-87},['icon'] = {"swd","u"}},
			['main_sw3'] = {['button_pos'] = {['x']=0.5,['y']=7.4},['pos']={['x']=443,['y']=2,['z']=-68},['icon'] = {"swd","u"}},
			['main_sw4'] = {['button_pos'] = {['x']=3.5,['y']=5.4},['pos']={['x']=441,['y']=2,['z']=-84},['icon'] = {"sw","d"}},
			['main_sw5'] = {['button_pos'] = {['x']=3.5,['y']=6.4},['pos']={['x']=485,['y']=2,['z']=-66},['icon'] = {"swd","u_rev"}},
			['main_sw6'] = {['button_pos'] = {['x']=3.5,['y']=7.4},['pos']={['x']=485,['y']=2,['z']=-81},['icon'] = {"swd","d_rev"}},
			['main_sw7'] = {['button_pos'] = {['x']=7.5,['y']=5.4},['pos']={['x']=497,['y']=2,['z']=-72},['icon'] = {"sw","u_rev"}},
			['main_sw8'] = {['button_pos'] = {['x']=7.5,['y']=6.4},['pos']={['x']=497,['y']=2,['z']=-75},['icon'] = {"sw","d_rev"}},
		}
	},
	[2] = {
		['header'] = {
			{command="addlabel",label="<--- SOUTH",X=icon_w*1,Y=0},
			{command="addlabel",label="NORTH --->",X=icon_w*7,Y=0},
			{command="addlabel",label="Main<->Testfield",X=bg.W/3,Y=0},
			{command="addlabel",label="Icefields Passing Loop",X=bg.W/3,Y=0.25},
			{command="addlabel",label="Cliffside Passing Loop",X=bg.W/3,Y=1.75},
			
		},
		['base_map'] = {			
			{blank,		ico("cnr","u",nil),	lin,	lin,					{"tf_2"},lin},
			{{"tf_1"},	lin,				lin,	ico("cnr","d_rev",nil)},
			
			{blank,ico("cnr","u",nil),lin,lin,{"tf_4"},lin},
			{{"tf_3"},lin,lin,ico("cnr","d_rev",nil)}
		},
		['labels'] = {
			{blank},
			{blank}
		},
		['sections'] = {
			{blank,		"272990",	{"272990"},	"272990","851349",	{"851349"}},
			{"986637",	{"986637"},	"948558",	"948558"},
			
			{blank,"903385",{"903385"},"903385","903385",{"481617"}},
			{{"851349"},{"614460"},"614460","614460"}
		},
		['points'] = {
			['tf_1'] = {['pos'] = {['x']=620,['y']=2,['z']=-66},['icon'] = {"swd","u"}},
			['tf_2'] = {['pos'] = {['x']=679,['y']=2,['z']=-8},['icon'] = {"sw","d_rev"}},
			
			['tf_3'] = {['pos'] = {['x']=926,['y']=2,['z']=150},['icon'] = {"sw","u"}},
			['tf_4'] = {['pos'] = {['x']=960,['y']=2,['z']=189},['icon'] = {"sw","d_rev"}},
		}
	}
}


--quick access to relevant map
local c_map = maps[S.active_map or 1]

--shorthand function to assemble the switch icon in current state
local pt = function(turnout)
	-- local id = c_map.points[turnout]
	local id = turnout
	if debug_state then print(id) end
	local state = getstate(id.pos)
	state = string.upper(state)
	local locked = ""
		if has_route_lock then -- check if function is available
			if has_route_lock(id.pos) then
				locked = "^[colorize:#FF0000"
			end
		end
	return	ico(id.icon[1],id.icon[2],state)..locked
end

if event.channel=="touch" then
	local msg = event.msg
	if type(c_map)=="table" then
		if c_map.points then
			for k,_ in pairs(msg) do
				if c_map.points[k] then
					local c_state = getstate(c_map.points[k]['pos'])
					local n_state = ""
					if c_state == "st" then
						n_state = "cr"
					else
						n_state = "st"
					end
					setstate(c_map.points[k]['pos'],n_state)
				end
			end
		end
	end
	update = true
end

--manual update by punching ops panel or luacontroller clock
if event.punch or (event.channel=="display" and event.msg=="update")then
	update = true
end



if update == true then
	----reset base layers
	local display = {
		{command="clear"},
		{command="addimage",texture_name=background,X=0,Y=0,W=bg.W,H=bg.H},
		{command="addbutton",name="update",label="Manual Refresh",X=7.5,Y=7.4,W=2.5,H=1},
	}
	
	if type(c_map)== "table" then
		--establish controls
		if c_map.points then
			for k,v in pairs(c_map.points) do
				if v.button_pos then
					if not v.display_name then v.display_name = k end
					table.insert(display,{command="addbutton",name=k,label=v.display_name,X=v.button_pos.x,Y=v.button_pos.y,W=2,H=1,})
				end
			end
		end
		
		--define complete map
		if c_map.base_map then
			for y,row in ipairs(c_map.base_map) do
				for x,v in ipairs(row) do
					if type(v)== "table" then v = pt(c_map.points[v[1]]) end
					if v ~= blank then
						if c_map.sections ~= nil then
							local show_ids = false
							local section = c_map.sections[y][x]
							if type(section) == "table" then
								section = section[1]
								show_ids = true
							end
							local sect_occ = section_occupancy(section)
							if type(sect_occ) == "table" and (sect_occ[1] ~= nil) then
								v = v..occupied
								if show_ids == true then
									table.insert(display,{
										command="addlabel",
										label=table.concat(sect_occ,", "),
										X=(icon_w*x)+offset_x,Y=(icon_h*y)+offset_y+0.3
									})
								end
							end
						end
						table.insert(display,{
							command="addimage",
							texture_name=v,
							X=(icon_w*x)+offset_x,Y=(icon_h*y)+offset_y,
							W=1.2*icon_w,H=icon_h
						})
					end
				end
			end
		end
		
		--add labels
		if c_map.labels then
			for y,row in ipairs(c_map.labels) do
				for x,v in ipairs(row) do
					if v ~= blank and v ~= nil then
						local pos = {['x'] = (icon_w*x)+offset_x, ['y'] = (icon_h*y)+offset_y-0.1}
						local label = ""
						if type(v) == "table" then
							label = v[1]
							if v[2] == "under" then pos.y = pos.y+0.5 end
						else
							label = v
						end
						table.insert(display,{
							command="addlabel",
							label=label,
							X=pos.x,Y=pos.y
							})
					end
				end
			end
		end
		
		--add headers/labels/graphics
		if c_map.header then
			for _,v in ipairs(c_map.header) do
				table.insert(display,v)
			end
		end
	else
		table.insert(display,{command="addlabel",label="Map "..tostring(S.active_map).." Not Defined Yet",X=1,Y=1})
	end
	--add debug train controls if enabled
	if debug_state then
		table.insert(display,{command="addbutton",name="send_train",label="Send Train",X=7.5,Y=7.5,W=2,H=1})
	end
	
	--draw
	digiline_send("touch",display)
end